package org.boge.sharpdoc.controller;

import org.boge.sharpdoc.bean.LayuiReturnData;
import org.boge.sharpdoc.service.SendMailService;
import org.boge.sharpdoc.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.Random;

@RestController
@RequestMapping("authCode")
public class AuthCodeController {
    @Autowired
    private HttpSession session;
    @Autowired
    private SendMailService sendMailService;

    @PostMapping("sendToPhone")
    public LayuiReturnData sendAuthCodeToPhone(String phone) {
        Integer num = new Random().nextInt(1000000);
        String checkCode = String.format("%06d", num);
        CommonUtil.sendCheckCodeToPhone(phone, checkCode);
        System.out.println(checkCode);
        session.setAttribute("checkCodePhone", checkCode);
        return new LayuiReturnData(0, true, "手机验证发已经发送，请注意查收。");
    }

    @PostMapping("sendToMail")
    public LayuiReturnData sendAuthCodeToMail(String emailaddr) throws MessagingException, UnsupportedEncodingException {
        Integer num = new Random().nextInt(1000000);
        String checkCode = String.format("%06d", num);
        session.setAttribute("checkCodeMail", checkCode);
        sendMailService.sendMailCheckCode(emailaddr, checkCode);
        return new LayuiReturnData(0, true, "验证码已发送到邮箱中");
    }
}